package com.dabai.app.im;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class JunHuaWebView extends WebView {

    private ProgressBar progressbar;
    private Context mContext;
    private int mProgressColor;
    private View failView;
    /*=============================================*/
    //mUrlList,mTitleMap解决webview.goBack()回退的时候，没有触发onReceiveTitle()的问题
    private List mUrlList = new ArrayList<String>();
    private HashMap mTitleMap = new HashMap();
    /*=============================================*/
    private WebViewCallBack webViewCallBack;

    public JunHuaWebView(Context context, AttributeSet attributeSet) {

        this(context, attributeSet, android.R.attr.webViewStyle);
    }

    public JunHuaWebView(Context context) {
        this(context, null);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public JunHuaWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(context, 3), 0, 0));

        failView = ViewUtils.getItemView(mContext, R.layout.item_net_error);
        failView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        failView.setVisibility(GONE);
        progressbar.setProgressDrawable(context.getResources().getDrawable(R.drawable.bar_bg));
        addView(progressbar);

        addView(failView);
        setWebChromeClient();
        addJavaScript(new BaseJsObject(mContext, this));
        getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        getSettings().setJavaScriptEnabled(true);
        getSettings().setAppCacheEnabled(true);

        getSettings().setDatabaseEnabled(true);
        //webView.getSettings().setAllowFileAccessFromFileURLs(true);
        //webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        getSettings().setDomStorageEnabled(true);
        getSettings().setSaveFormData(true);
        // webView.getSettings().setUseWideViewPort(true);
        getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        requestFocus();

       /* View view=ViewUtils.getItemView(context, R.layout.item_webview);
        mProgress=(ProgressBar)view.findViewById(R.id.webview_progress);
        TypedArray typedArray=context.getTheme().obtainStyledAttributes(attrs,R.styleable.JunHuaWebView,defStyleAttr,0);
        int n=typedArray.getIndexCount();

        for(int i=0;i<n;i++){
            int attr = typedArray.getIndex(i);
            switch (attr){
                case R.styleable.JunHuaWebView_progressColor:
                     mProgressColor=typedArray.getColor(attr,context.getResources().getColor(R.color.common_top_bar_blue));
                    break;
            }
        }*/
    }

    private void setWebChromeClient() {

        this.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTitleMap.put(JunHuaWebView.this.getUrl(), title);
                if (webViewCallBack != null && !TextUtils.isEmpty(title) && !title.contains(".com")) {
                    webViewCallBack.onTitleChange(title);
                }
//                webViewCallBack.onCanGoBack(JunHuaWebView.this.canGoBack());
                webViewCallBack.onCanGoBack(mUrlList.size() == 1 ? false : true);
            }

            @Override
            public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }


            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                progressbar.setProgress(newProgress);
                progressbar.setVisibility(View.VISIBLE);
                if (progressbar.getMax() == newProgress) {
                    progressbar.setVisibility(View.GONE);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, final String message, JsResult result) {


                //super.onJsAlert(view,url,message,result);
           /*   UIThread.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtil.showDialogNoTitle(mContext, message, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                    }
                });*/

                return super.onJsAlert(view, url, message, result);

            }


            @Override
            public boolean onJsConfirm(WebView view, String url, final String message, JsResult result) {

                return super.onJsConfirm(view, url, message, result);
            }
        });
        this.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                webViewCallBack.onCanGoBack(mUrlList.size() == 1 ? false : true);
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mUrlList.add(url);
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    mContext.startActivity(intent);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) {

                failView.setVisibility(VISIBLE);
                failView.findViewById(R.id.net_error_iv).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        failView.setVisibility(GONE);
//                        loadUrl(failingUrl);
                        reload();
                        for (int i = 0; i < mUrlList.size(); i++) {
                            if (mUrlList.get(i).equals(failingUrl)) {
                                mUrlList.remove(i);
                            }
                        }
                    }
                });
//                webViewCallBack.onCanGoBack(JunHuaWebView.this.canGoBack());
                webViewCallBack.onCanGoBack(mUrlList.size() == 1 ? false : true);

                //super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        this.setAlwaysDrawnWithCacheEnabled(true);

    }

    @SuppressLint("JavascriptInterface")
    public void addJavaScript(Object object) {
        this.addJavascriptInterface(object, "JavaScriptInterface");
    }


    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
        lp.x = l;
        lp.y = t;
        progressbar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }

    @Override
    public void loadUrl(String url) {
        super.loadUrl(url);
    }

    public WebViewCallBack getWebViewCallBack() {
        return webViewCallBack;
    }

    public void setWebViewCallBack(WebViewCallBack webViewCallBack) {
        this.webViewCallBack = webViewCallBack;
    }

    public interface WebViewCallBack {

        public void onTitleChange(String title);

        public void onCanGoBack(boolean canGoBack);

    }

    public List getUrlList() {
        return mUrlList;
    }

    public void setUrlList(List urlList) {
        mUrlList = urlList;
    }

    public HashMap getTitleMap() {
        return mTitleMap;
    }

    public void setTitleMap(HashMap titleMap) {
        mTitleMap = titleMap;
    }
}
